import { get, post } from '@/utils/service'
import { SESSION_LAST_CODE, SESSION_MEMBER_INFO } from '@/utils/baseConfig'
import wx from 'weixin-js-sdk'
import { showToast } from 'vant'
export const shareType = {
  SHARE_WECHAT_ACTITY: 1,
  SHARE_WECHAT_NEWS: 2,
}
export function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
// 保存分享记录
function saveShareRecord(shareData: object) {
  const code = localStorage.getItem(SESSION_LAST_CODE)
  const memberInfo = localStorage.getItem(SESSION_MEMBER_INFO + code)
  const member = JSON.parse(memberInfo)
  const reqData = {
    memberId: member.dbid,
    timestamp: Date.now(),
    extraData: shareData.extraData || '',
    shareRecordNo: shareData.shareRecordNo,
    path: shareData.link,
    title: shareData.title,
    imageUrl: shareData.imgUrl,
    type: shareData.shareType, //
    appType: 1, //应用分享类型：1小程序分享；2、公众号分享
  }
  post('/dataShareRecordWechatNew/saveWechatShare', reqData).then((res) => {
    if (res.code == 0) {
      showToast('分享成功')
    }
  })
}
//初始化分享信息
export async function initWehcatShare(
  shareData: object,
  url: string,
  isWechatState: boolean,
  shareType: number,
) {
  if (!isWechatState) {
    //不是微信号取消分享程序
    return
  }
  // 步骤1：获取签名所需参数（需要后端接口支持）
  // 注意：当前URL需要动态获取，并且需要与后端生成签名时使用的URL一致（不包括#及其后面部分）
  const shareRecordNo = generateUUID()
  const code = localStorage.getItem(SESSION_LAST_CODE)
  const memberInfo = localStorage.getItem(SESSION_MEMBER_INFO + code)
  const member = JSON.parse(memberInfo)
  shareData.shareRecordNo = shareRecordNo
  shareData.shareType = shareType

  try {
    get('/dataShareRecordWechatNew/queryWeixinShareSign', { url: url }).then((res) => {
      if (res.code != 0) {
        console.log(res.msg)
        return
      }
      const { appId, timestamp, nonceStr, signature } = res.data
      //封装新的分享参数
      const arrays = url.split('?')
      url = arrays[0]
      let params
      if (arrays[1] != null || arrays[1] != undefined) {
        params = arrays[1].split('&')
      }
      if (params != null && params.length > 0) {
        url = url + '?' + params[0]
      }
      url = url + '&' + shareRecordNo + '&shareMemberId=' + member.dbid
      // 步骤2：配置JS-SDK
      wx.config({
        debug: false, // 生产环境建议关闭
        appId,
        timestamp,
        nonceStr,
        signature,
        jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'], // 需要使用的JS接口列表
      })

      // 步骤3：处理验证成功后的逻辑
      wx.ready(() => {
        // 配置分享给朋友
        wx.updateAppMessageShareData({
          title: shareData.title,
          desc: shareData.desc,
          link: url,
          imgUrl: shareData.imgUrl,
          success: () => {
            console.log('updateAppMessageShareData :success')
            // 设置成功
            // saveShareRecord(shareData)
          },
          fail: (res) => {
            console.log('fail:' + res)
          },
          complete: (res) => {
            console.log('complete:' + JSON.stringify(res))
          },
          cancel: (res) => {
            console.log('cancel:' + res)
          },
        })

        // 配置分享到朋友圈
        wx.updateTimelineShareData({
          title: shareData.title, // 朋友圈分享只显示标题，所以标题要吸引人
          link: url,
          imgUrl: shareData.imgUrl,
          success: () => {
            console.log('updateTimelineShareData :success')
            // 设置成功
            // saveShareRecord(shareData)
          },
        })
        /* wx.onMenuShareTimeline({
          title: shareData.title, // 朋友圈分享只显示标题，所以标题要吸引人
          link: url,
          imgUrl: shareData.imgUrl,
          success: function () {
            // 用户点击了分享后执行的回调函数
            alert('onMenuShareTimeline')
            saveShareRecord(shareData)
          },
          cancel: function () {},
        })
        wx.onMenuShareAppMessage({
          title: shareData.title,
          desc: shareData.desc,
          link: url,
          imgUrl: shareData.imgUrl,
          success: function () {
            // 用户点击了分享后执行的回调函数
            alert('onMenuShareAppMessage')
            saveShareRecord(shareData)
          },
          cancel: function () {},
        }) */
      })
      // 处理验证失败
      wx.error((res) => {
        console.error('微信JS-SDK配置失败', res)
      })
    })
  } catch (error) {
    console.error('获取签名失败', error)
  }
}
